package top.lshaci.learning.springboot.es.config;

import lombok.AllArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import static cn.hutool.core.util.StrUtil.COMMA;

/**
 * ElasticsearchConfig
 *
 * @author lshaci
 * @since 1.0.0
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchConfig {

    private final ElasticsearchProperties properties;

    @Bean
    public RequestOptions requestOptions() {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        return builder.build();
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() throws MalformedURLException {
        String nodes = properties.getClusterNodes();
        Assert.hasText(nodes, "[Assertion Failed] At least one host must be set.");
        ArrayList<HttpHost> httpHosts = new ArrayList<>();
        for (String host : nodes.split(COMMA)) {
            URL hostUrl = new URL(host);
            httpHosts.add(new HttpHost(hostUrl.getHost(), hostUrl.getPort(), hostUrl.getProtocol()));
        }
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts.toArray(new HttpHost[httpHosts.size()])));
        return client;
    }
}
